﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Data;
using System.Windows;
using Modules.Core;
using System.Windows.Input;
using ComputerStoreManager.Controls;
using Modules.Library.Entities;

namespace ComputerStoreManager.ViewModel.Invoice {
    class AddInvoiceControlViewModel : BaseViewModel {
        private TextBox txtAmount;
        private TextBox txtDate;
        private TextBox txtInvoiceId;
        //private TextBox txtNumber;
        //private TextBox txtSalePrice;
        private TextBox cbbEmpId;
        //private ComboBox cbbProductName;
        private Button btnAdd;
        private Button btnClear;
        private Button btnPurchase;
        private Button btnSub;
        //private ComboBox cbbCustomerId;
        private List<ProductItem> items;
        private ListBox listMatHang;
        private List<InvoiceDetail> listInvoiceDetail;
        private DataTable productTable;

        #region ICommand
        public ICommand AddCommand {
            get;
            private set;
        }
        public ICommand SubCommand {
            get;
            private set;
        }
        public ICommand ClearCommand {
            get;
            private set;
        }
        public ICommand PurchaseCommand {
            get;
            private set;
        }

        #endregion

        public override void InitControlInfo() {
            try
            {
                txtInvoiceId.Text = Converter.ConvertToId(Model.GetThongSoPhu(KindOfObject.BY_INVOICE));
                txtAmount.Text = "0";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi thao tác " + ex.Message, "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        public AddInvoiceControlViewModel(TextBox txtAmount, TextBox txtDate, TextBox txtInvoiceId, TextBox cbbEmpId, Button btnAdd, ListBox listMatHang, Button btnClear, Button btnPurchase, Button btnSub) {
            // TODO: Complete member initialization
            this.txtAmount = txtAmount;
            this.txtDate = txtDate;
            this.txtInvoiceId = txtInvoiceId;
            this.cbbEmpId = cbbEmpId;
            //this.cbbCustomerId = cbbCustomerId;
            this.btnAdd = btnAdd;
            this.btnClear = btnClear;
            this.btnPurchase = btnPurchase;
            this.btnSub = btnSub;
            this.listMatHang = listMatHang;
            items = new List<ProductItem>();
            listInvoiceDetail = new List<InvoiceDetail>();

            this.cbbEmpId.Text = LoginPanel.MaNhanVien;
            this.txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");

            AddCommand = new ExecutableCommand(DoAdd);
            SubCommand = new ExecutableCommand(DoSub);
            ClearCommand = new ExecutableCommand(DoClearFields);
            PurchaseCommand = new ExecutableCommand(DoPurChaseInvoice);
            InitControlInfo();
        }

        public override bool CheckIsNotNull() {
            return txtAmount.Text != "" &&
                txtDate.Text != "" &&
                txtInvoiceId.Text != "";
            //txtNumber.Text != "" &&
            //txtSalePrice.Text != "";
        }

        private void DoPurChaseInvoice() {
            try {
                if (CheckIsNotNull()) {

                    Modules.Library.Entities.Invoice invoice = new Modules.Library.Entities.Invoice();
                    invoice.GiaBan = txtAmount.Text;
                    invoice.MaHoaDonBan = txtInvoiceId.Text;
                    invoice.MaKhachHangMua = "MKH0";
                    invoice.MaNhanVienBan = cbbEmpId.Text;
                    invoice.NgayBan = DateTime.Parse(Converter.ConvertToDateTime(txtDate.Text, Converter.MMDDYYYY));
                    //invoice.SoLuongBan = txtNumber.Text;
                    //invoice.TenSanPham = cbbProductName.SelectedItem.ToString();
                    invoice.TongTien = txtAmount.Text;

                    if (!Model.InsertNewData(invoice, KindOfObject.BY_INVOICE)) {
                        MessageBox.Show(Model.Error);
                        DoClearFields();
                    }
                    else {
                        
                        //MessageBox.Show(Constants.SUCCESS);
                        int counter = 0;
                        foreach (var dt in listInvoiceDetail) {
                            counter++;
                            if (!Model.InsertNewData(dt, KindOfObject.BY_INVOICEDETAILS)) {
                                MessageBox.Show(Model.Error);
                            }
                            else {
                                UpdateProduct(dt.MaMH, int.Parse(dt.SoLuongBan));
                                //MessageBox.Show(Constants.SUCCESS);
                            }
                        }
                        MessageBox.Show(Constants.SUCCESS);
                        DoClearFields();
                    }

                }
                else {
                    MessageBox.Show("Bạn không được bỏ trống bất kỳ trường nào.", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex) {
                MessageBox.Show("Lỗi thao tác " + ex.Message, "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void UpdateProduct(string maMH, int soLuong)
        {
            try
            {
                Connection con = new Connection();
                Product product = new Product();
                productTable = con.GetDataTable("select * from linhkien where MaMH = '" + maMH + "';");
                con.Disconnect();
                product.AnhDaiDien = "";
                product.ChiTietLinhKien = null;
                product.GhiChu = productTable.Rows[0]["GhiChu"].ToString();
                product.GiaBan = productTable.Rows[0]["GiaBan"].ToString();
                product.GiaMua = productTable.Rows[0]["GiaMua"].ToString();
                product.MaLoaiMatHang = productTable.Rows[0]["MaLoaiMH"].ToString();
                product.MaMatHang = maMH;
                product.NhaCungCap = productTable.Rows[0]["TenNCC"].ToString();
                product.NhaSanXuat = productTable.Rows[0]["TenNSX"].ToString();
                product.SoLuongTonKho = Convert.ToInt32(productTable.Rows[0]["SoLuongTonKho"].ToString()) - soLuong;
                product.TenMatHang = productTable.Rows[0]["TenMH"].ToString();

                if (!Model.UpdateData(product, KindOfObject.BY_PRODUCT))
                {
                    MessageBox.Show("Lỗi");
                }
                else
                {
                    MessageBox.Show("Thành Công");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi thao tác " + ex.Message, "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        public override void DoClearFields() {
            this.txtAmount.Text = string.Empty;
            //this.txtDate.Text = string.Empty;
            this.txtInvoiceId.Text = string.Empty;
            listMatHang.Items.Clear();

            InitControlInfo();
            //this.txtNumber.Text = string.Empty;
            //this.txtSalePrice.Text = string.Empty;
        }

        private void DoAdd() {
            //tạo thêm các line
            try
            {
                ProductItem item = new ProductItem();
                item.OnOkEventHandler += item_OnOkEventHandler;
                items.Add(item);
                listMatHang.Items.Add(item);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi thao tác " + ex.Message, "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        void item_OnOkEventHandler(double e, string maMH, string giaBan, string soLuongBan) {
            try
            {
                txtAmount.Text = (double.Parse(txtAmount.Text) + e).ToString();
                InvoiceDetail d = new InvoiceDetail();
                d.GiaBan = giaBan;
                d.MaHDBan = txtInvoiceId.Text;
                d.MaKhuyenMai = "0";
                d.MaMH = maMH;
                d.SoLuongBan = soLuongBan;
                d.TongTien = e.ToString();

                listInvoiceDetail.Add(d);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi thao tác " + ex.Message, "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
            }

        }

        //void item_OnOkEventHandler(double e) {
        //    txtAmount.Text = (double.Parse(txtAmount.Text) + e).ToString();
        //}
        private void DoSub() {
            try
            {
                if (listMatHang.Items.Count >= 1)
                {
                    listMatHang.Items.RemoveAt(listMatHang.Items.Count - 1);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi thao tác " + ex.Message, "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
    }
}
